/**
 * @description 两数之和
 * @author  李子一
 */

/**
 * 嵌套循环查找两数之和
 */
export function findTwoNumbers1(arr: number[], n: number): number[] {
	const res: number[] = []
	const length = arr.length
	if (!length) return res

	for (let i = 0; i < length; i++) {
		const n1 = arr[i]
		let flag = false
		for (let j = i + 1; j < length; j++) {
			const n2 = arr[j]

			if (n1 + n2 === n) {
				res.push(n1, n2)
				flag = true
				break
			}
		}
		if (flag) break
	}

	return res
}

// 双指针法
export function findTwoNumbers2(arr: number[], n: number): number[] {
	const length = arr.length
	if (!length) return []
	let startIndex = 0,
		endIndex = length - 1

	while (startIndex <= endIndex) {
		if (arr[startIndex] + arr[endIndex] < n) {
			startIndex++
		} else if (arr[startIndex] + arr[endIndex] > n) {
			endIndex--
		} else {
			return [arr[startIndex], arr[endIndex]]
		}
	}
	return []
}
